// 主题切换组合式函数
export const useTheme = () => {
  const isDark = ref(false)
  
  // 初始化主题
  const initTheme = () => {
    if (process.client) {
      // 从localStorage读取主题设置
      const savedTheme = localStorage.getItem('theme')
      if (savedTheme) {
        isDark.value = savedTheme === 'dark'
      } else {
        // 根据系统偏好设置主题
        isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches
      }
      applyTheme()
    }
  }
  
  // 应用主题
  const applyTheme = () => {
    if (process.client) {
      const html = document.documentElement
      if (isDark.value) {
        html.classList.add('dark')
      } else {
        html.classList.remove('dark')
      }
      localStorage.setItem('theme', isDark.value ? 'dark' : 'light')
    }
  }
  
  // 切换主题
  const toggleTheme = () => {
    isDark.value = !isDark.value
    applyTheme()
  }
  
  // 设置主题
  const setTheme = (theme: 'light' | 'dark') => {
    isDark.value = theme === 'dark'
    applyTheme()
  }
  
  // 监听系统主题变化
  const watchSystemTheme = () => {
    if (process.client) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      const handleChange = (e: MediaQueryListEvent) => {
        if (!localStorage.getItem('theme')) {
          isDark.value = e.matches
          applyTheme()
        }
      }
      mediaQuery.addEventListener('change', handleChange)
      
      // 返回清理函数
      return () => mediaQuery.removeEventListener('change', handleChange)
    }
  }
  
  // 在客户端初始化
  onMounted(() => {
    initTheme()
    const cleanup = watchSystemTheme()
    onUnmounted(() => {
      if (cleanup) cleanup()
    })
  })
  
  return {
    isDark: readonly(isDark),
    toggleTheme,
    setTheme,
    initTheme
  }
}
